package com.xxxx.comment.exception;

import com.xxxx.comment.entity.dto.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

@Slf4j
@RestControllerAdvice
public class WebExceptionAdvice
{
    @ExceptionHandler(RuntimeException.class)
    public Result handleRuntimeException(RuntimeException e)
    {
        log.error(e.toString(), e);
        return Result.fail(e.toString().substring(e.toString().indexOf(":") + 1));
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleException(MethodArgumentNotValidException e)
    {
        log.error(e.toString());
        return Result.fail(e.getLocalizedMessage().substring(
                e.getLocalizedMessage().lastIndexOf("[") + 1,
                e.getLocalizedMessage().lastIndexOf("]") - 1)
        );
    }

    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public Result handleArgumentMismatchException(MethodArgumentTypeMismatchException e)
    {
        log.error(e.getMessage(), e);
        return Result.fail("请求参数错误");
    }

    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e)
    {
        log.error(e.toString());
        return Result.fail("系统错误，请联系管理员！");
    }
}
